#!/bin/bash
set -uex
cd "$GCS_APP_PATH"
if [ -f gcs_default_env.sh ];then
    source gcs_default_env.sh
fi
ENTRY_FILENAME="${GCS_ENTRY_FILENAME:-app.py}"
START_COMMAND="python ${GCS_APP_PATH}/${ENTRY_FILENAME} --port=${GCS_CUSTOM_PORT}"
TIME_WAIT=4

help(){
    echo "${0} <install|start|stop|restart|status>"
    exit 1
}

install(){
    if [ -f install.sh ];then
        bash install.sh
    else
        local requirements_file="${GCS_APP_PATH}/requirements.txt"
        if [ -f "$requirements_file" ]; then
            pip install -r "$requirements_file"
        fi
    fi
}

get_pid(){
    echo $(pgrep -f "${START_COMMAND}")

}

checkhealth(){
    pid=$(get_pid)
    if [ ! -z "$pid" ]; then
        echo "App is running."
        return 0
    else
        echo "App is not running."
        return 1
    fi
}

start(){
    if checkhealth; then
        echo "App is already running."
        exit 1
    fi
    nohup $START_COMMAND > /proc/1/fd/1 2>&1 &
    echo "App started."
}

stop(){
    if ! checkhealth; then
        echo "App is not running."
        return 0
    fi
    pid=$(get_pid)
    if [ ! -z "$pid" ]; then
        kill -9 "$pid"
        sleep $TIME_WAIT
        if ! checkhealth; then
            echo "App stopped."
            return 0
        else
            echo "Failed to stop the app."
            return 1
        fi
    fi
}

case "${1}" in
    install)
        install
        ;;
    start)
        start
        ;;
    stop)
        stop
        ;;
    status|health|checkhealth)
        checkhealth
        ;;
    restart)
        stop && start
        ;;
    *)
        help
        ;;
esac